package com.xiaojie.redisson.redlock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonRedLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author xiaojie
 * @version 1.0
 * @description: 测试redlock
 * @date 2022/4/1 22:50
 */
//@RestController
@Slf4j
public class RedissonController {

    @Autowired
    @Qualifier("redissonClient1")
    private RedissonClient redissonClient1;
    @Autowired
    @Qualifier("redissonClient2")
    private RedissonClient redissonClient2;
    @Autowired
    @Qualifier("redissonClient3")
    private RedissonClient redissonClient3;
    @RequestMapping("/testReddisson")
    public String testReddisson(Long id ){
        //获取reddisson锁
        RLock lock1 = redissonClient1.getLock(id + "");
        RLock lock2 = redissonClient2.getLock(id + "");
        RLock lock3 = redissonClient3.getLock(id + "");
        RedissonRedLock lock = new RedissonRedLock(lock1, lock2, lock3);
        try {
//            lock.tryLock();
            lock.tryLock(60,60, TimeUnit.SECONDS);
            log.info("开始执行业务逻辑");
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (null!=lock){
                //释放锁
                lock.unlock();
            }
        }
        return "failure";
    }
}
